package com.example.spotify_plugin_t;

import android.app.Activity;
import android.content.Intent;
import android.preference.PreferenceManager;

import androidx.annotation.NonNull;

import com.spotify.sdk.android.auth.AuthorizationClient;
import com.spotify.sdk.android.auth.AuthorizationRequest;
import com.spotify.sdk.android.auth.AuthorizationResponse;

import java.util.HashMap;
import java.util.Set;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;

/**
 * SpotifyPlugin_tPlugin
 */
public class SpotifyPlugin_tPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware, PluginRegistry.ActivityResultListener {
    private MethodChannel channel;

    /**
     * 事件通道，用来发消息给flutter
     */
    private EventChannel.EventSink sink;
    private  EventChannel eventChannel;

//    public static String CLIENT_ID;// = "97554c79a165469995958c4bd217d80f";
//    public static String REDIRECT_URI;// = "spotify-sdk://auth";
//    public static String SCOPE;// 以英文逗号,作为分隔符

    public static final int AUTH_TOKEN_REQUEST_CODE = 0x10;
    public static final int AUTH_CODE_REQUEST_CODE = 0x11;

    Result result_spotifyCode;

    /**
     * 用来获取当前Context
     */
    private Activity activity;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "spotify_plugin_t");
        channel.setMethodCallHandler(this);

        System.out.println("执行了吗");
        //初始化事件通道，主要是获取这个EventChannel.EventSink sink，用这个sink发消息给flutter
        eventChannel = new EventChannel(flutterPluginBinding.getBinaryMessenger(), "spotify_plugin_t_eventChannel");
        eventChannel.setStreamHandler(new EventChannel.StreamHandler() {
            @Override
            public void onListen(Object o, EventChannel.EventSink eventSink) {
                System.out.println("sink 赋值");
                sink = eventSink;
            }

            @Override
            public void onCancel(Object o) {
                sink = null;
            }
        });

    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        if (call.method.equals("getPlatformVersion")) {
            result.success("Android " + android.os.Build.VERSION.RELEASE);
        }
        if (call.method.equals("getSpotifyCode")) { //获取spotify code
            HashMap argumentsMap = (HashMap) call.arguments;
            String clientId = argumentsMap.get("clientId").toString();
            String url = argumentsMap.get("url").toString();
            String scope = argumentsMap.get("scope").toString();

            String[] scopeList = null;
            if (scope != null) {
                scopeList = scope.split(",");
            }
            final AuthorizationRequest request = getAuthenticationRequest(AuthorizationResponse.Type.CODE,clientId,url,scopeList);

            AuthorizationClient.openLoginActivity(activity, AUTH_CODE_REQUEST_CODE, request);
            result_spotifyCode = result;


        } else if (call.method.equals("getSpotifyToken")) { //获取spotify token
            HashMap argumentsMap = (HashMap) call.arguments;
            String clientId = argumentsMap.get("clientId").toString();
            String url = argumentsMap.get("url").toString();
            String scope = argumentsMap.get("scope").toString();

            String[] scopeList = null;
            if (scope != null) {
                scopeList = scope.split(",");
            }
            final AuthorizationRequest request = getAuthenticationRequest(AuthorizationResponse.Type.TOKEN,clientId,url,scopeList);

            AuthorizationClient.openLoginActivity(activity, AUTH_TOKEN_REQUEST_CODE, request);
            result_spotifyCode = result;
        }
        else {
            result.notImplemented();
        }
    }

    private AuthorizationRequest getAuthenticationRequest(AuthorizationResponse.Type type,String clientId,String url,String[] scopes) {
        System.out.println("spotify auth clientId " + clientId);
        System.out.println("url " + url);
        System.out.println("scopes" + scopes.toString());
        return new AuthorizationRequest.Builder(clientId, type, url)
                .setShowDialog(false)
                .setScopes(scopes)
                .build();
    }

    @Override
    public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        System.out.println("spotify_plugin_t onActivityResult");
        if (data == null) {
            return false;
        }

        final AuthorizationResponse response = AuthorizationClient.getResponse(resultCode, data);

        System.out.println("spotify auth ycflutter response error = " + response.getError());
        System.out.println("ycflutter response = " + response.toString());
        System.out.println("ycflutter requestCode = " + requestCode);
        if (AUTH_TOKEN_REQUEST_CODE == requestCode) {
            String accessToken = response.getAccessToken();
            System.out.println("ycflutter accessToken = " + accessToken);
            if (accessToken == null) {
                accessToken = "";
            }

            if (result_spotifyCode != null) {
                result_spotifyCode.success(accessToken);
            }

            return true;

        } else if (AUTH_CODE_REQUEST_CODE == requestCode) { // 返回spotify code
            String accessCode = response.getCode();
            System.out.println("ycflutter accessCode = " + accessCode);
            if (accessCode == null) {
                accessCode = "";
            }
            if (result_spotifyCode != null) {
                result_spotifyCode.success(accessCode);
            }
            return true;
        }
        return true;
    }


    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    /**
     * ActivityAware 用来获取Context applicationContext = activity.getApplicationContext()
     */
    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
        binding.addActivityResultListener(this);
        activity = binding.getActivity();
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {
        this.onDetachedFromActivity();
    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
        this.onAttachedToActivity(binding);
    }

    @Override
    public void onDetachedFromActivity() {
        activity = null;
    }


}
